<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {
	public function login() {
		header("Content-type: application/json");
		// 取出参数
		$openid = $this->input->get('openid');
		if (empty($openid)) {
			echo json_encode(array('code' => 400, 'msg' => '参数错误','data' => []));
			return ;
		}
		
		// 查询数据库
		$query = $this->db->query("select * from user where openid = '" . $openid . "'");
		// 返回行数，大于0意味着该用户已经存在
		if ($query->num_rows() > 0) {
			// 取出该用户
			$user = $query->first_row();
			// 输出用户的信息
			echo json_encode(array('code' => 200, 'msg' => '登录成功','data' => $user));
			return;
		}
		
		// 注册用户
		$user = array(
				'nickname' => $openid,
				'openid' => $openid,
				'accessToken' => md5(time().'mysalt')
			);
		$this->db->insert('user', $user);
		// 返回该查询的id
		$insert_id = $this->db->insert_id();
		// 追加到user
		$user['uid'] = $insert_id;
		echo json_encode(array('code' => 200, 'msg' => '注册成功','data' => $user));
		return;
	}
}